﻿using QDAS;
using QDasConverter.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;



namespace QDasConverter.Core
{
    public class C2021T09_Excel : ConvertBase
    {

        /// <summary>
        /// 需要进行转换的数据目录，每个目录下包括巨一的CSV文件列表。注意：程序不转换子目录下的CSV文件。
        /// </summary>

        Dictionary<string, string> opindices = new Dictionary<string, string>();
        Dictionary<string, Chs> dics = new Dictionary<string, Chs>();
        
        bool NeedBackup = true;
        // 路径配置文件
        string TargetDirectory = @"D:\qdas_syn\syn_file\jy";


        struct Chs
        {
            public string code;
            public string testItem;
            public string k2101;
            public string k2110;
            public string k2111;
            public string consoleType;
            public string remark;
            public string k2005;
           
        }

        public C2021T09_Excel()
        {
            NeedConnectionCheck = false;
            DisplayName = "巨一 转换器";
            Version = "beta1 Released Date: 2022/06/09 Inner Name: C2021T09_Excel";


            // 2022/06/09 机器号对应CATALOG值
            var data = new string[] { "DCT-0180-1,1108010","DCT-0180-2,1108015", "DCT-0190-1,1108040", "MID-0020-1,1108025", "MID-0030-1,1108045"};
            foreach (var item in data) {
                var strs = item.Split(',');
                opindices.Add(strs[0], strs[1]);
            }



        }

        
        /// <summary>
        /// 设置为True，保证一直转换。
        /// </summary>
        /// <returns></returns>
        public override bool NeedConvert() => true;


        public override bool OnStart()
        {

            Console.WriteLine(opindices);

            // 测试模式使用
            if (DebugMode)
            {
                ProcessDirectory(@"..\..\samples\kistler\MP-009\");

                SqlConnectionString = "Data Source = 112.74.87.167;Initial Catalog = cvinet;User ID = sa; Password = root00;";
                sm = new WindGoes6.Database.SQLManager(SqlConnectionString);
            }



            //获取数据灵活配置的上下限
            string constr = "Data Source =10.0.7.186;Initial Catalog = chystat; User ID = sa; Password = Temp@pass;"; // 远程连接
            //string constr = "Data Source =112.74.87.167;Initial Catalog = chystat; User ID = sa; Password = root00;"; // 远程连接

            psm = new WindGoes6.Database.SQLManager(constr);
            psm.CommandText = "SELECT code,test_item,name_value_k2101,low_value_k2110,high_value_k2111,console_type,remark,cpk_level,id FROM chystat.dbo.properties WHERE tool_type = 9";
            var data = psm.GetStrings();

            foreach (var items in data)
            {

                var chs = new Chs()
                {
                    code = items[0].Trim(),
                    testItem = items[1].Trim(),
                    k2101 = items[2].Trim(),
                    k2110 = items[3].Trim(),
                    k2111 = items[4].Trim(),
                    consoleType = items[5].Trim(),
                    remark = items[6].Trim(),
                    k2005 = items[7].Trim()
                };
                if (!dics.ContainsKey(chs.code))
                    dics.Add(items[0].Trim(), chs);
            }

            return true;
        }


        public override void OneLoop_Process()
        {
            if (!Directory.Exists(TargetDirectory))
            {
                Console.WriteLine($"Directory {TargetDirectory} does not exist.");
                return;
            }

            var subdirs = Directory.GetDirectories(TargetDirectory);
            foreach (var subdir in subdirs)
                ProcessDirectory(subdir);
        }

        private void ProcessDirectory(string sphfile_dir)
        {
            // 如果以是 _backup 为后缀名，则是备份文件夹，不用处理
            if (sphfile_dir.ToLower().EndsWith("_backup"))
                return;

            // 如果需要备份则创建备份文件夹
            var pathb = sphfile_dir + "_backup"; // 备份文件夹
            if (NeedBackup && !Directory.Exists(pathb))
                Directory.CreateDirectory(pathb);

            try
            {
                foreach (var xlsfile in Directory.GetFiles(sphfile_dir))
                {

                    var lines = File.ReadAllLines(xlsfile, Encoding.UTF8);
                    if (lines == null)
                    {
                        continue;
                    }

                    List<string[]> csvcontent = new List<string[]>();

                    foreach (var line in lines)
                    {
                        csvcontent.Add(line.Split(','));
                    }

                    QFile qf = new QFile();
                    qf[1001] = csvcontent[0][0];
                    qf[1002] = csvcontent[0][0];
                    qf[1086] = csvcontent[0][3];
                    qf[1206] = "巨一";
                    qf[1203] = "气密";

                    string[] station_num = { "10", "11", "12", "13", "14", "15" };

                    foreach (var item in csvcontent)
                    {
                        //过滤需要的值目前只需要10-15的数据
                        if (Array.IndexOf(station_num, item[4]) != -1)
                        {
                            // 添加参数层
                            QCharacteristic qc = qf.AddQCharacteristic();
                            if (dics.ContainsKey(item[3] + "-" + item[4]))
                            {
                                var chi = dics[item[3] + "-" + item[4]];
                                qc[2002] = chi.testItem;
                                qc[2101] = chi.k2101;
                                qc[2110] = chi.k2110;
                                qc[2111] = chi.k2111;
                                qc[2005] = chi.k2005;
                            }
                            qc[2142] = "mm";
                            DateTime dt = DateTime.Parse(item[2]);

                            QDataItem qv1 = qc.AddItem();
                            qv1.SetValue(item[5]);
                            qv1.date = dt;
                            qv1[0014] = item[1];
                            qv1[0010] = opindices.ContainsKey(item[3]) ? opindices[item[3]] : "";

                        }
                    }
                    // 保存文件
                    qf.ToDMode();
                    SaveToDFQ(qf, OutputDirectory, "JY_" + DateTime.Now.ToString("yyyyMMdd_HHmmss.fff"));
                    CopyFileTo(xlsfile, pathb, true);




                    //    var sheet = ExcelHelper.LoadWorkSheet(xlsfile, 0);
                    //    if (sheet == null)
                    //        continue;





                    //    qf[1001] = sheet["A1"].Value;
                    //    qf[1002] = sheet["A1"].Value;
                    //    qf[1206] = "巨一";

                    //    qf[0100] = sheet["C5"].Value;


                    //    var qc1 = qf.AddQCharacteristic();
                    //    qc1[2001] = "1";
                    //    qc1[2002] = sheet["D4"].Value;


                    //    var qc2 = qf.AddQCharacteristic();
                    //    qc2[2001] = "2";
                    //    qc2[2002] = sheet["E4"].Value;


                    //    var qc3 = qf.AddQCharacteristic();
                    //    qc3[2001] = "3";
                    //    qc3[2002] = sheet["F4"].Value;

                    //    var qc4 = qf.AddQCharacteristic();
                    //    qc4[2001] = "4";
                    //    qc4[2002] = sheet["G4"].Value;

                    //    var dt = DateTime.Now;

                    //    int i = 0;
                    //    foreach (var row in sheet.Rows)
                    //    {
                    //        if (i > 4)
                    //        {
                    //            dt = DateTime.Parse(row["B" + i].Value.ToString());
                    //            var qd1 = qc1.AddItem();
                    //            qd1.SetValue(row["D" + i].Value.ToString());
                    //            qd1.date = dt;
                    //            qd1[0014] = row["A" + i].Value.ToString();
                    //            qd1[1002] = row["C" + i].Value.ToString();

                    //            var qd2 = qc2.AddItem();
                    //            qd2.SetValue(row["E" + i].Value.ToString());
                    //            qd2.date = dt;

                    //            var qd3 = qc3.AddItem();
                    //            qd3.SetValue(row["F" + i].Value.ToString());
                    //            qd3.date = dt;

                    //            var qd4 = qc4.AddItem();
                    //            qd4.SetValue(row["G" + i].Value.ToString());
                    //            qd4.date = dt;
                    //        }
                    //        i++;
                    //    }
                    //    qf.ToDMode();


                    //    SaveToDFQ(qf, OutputDirectory, $"C098_{qf[0100]}_{dt:yyyyMMddHHmmss}_{NowString()}.dfq");

                }
            }catch(Exception ex)
            {
                Common.AddLog(ex.Message);
            }
        }
    }
}
